# coding: utf-8

from PySide6.QtGui import QResizeEvent
from qeventmanager import qevent_manager
from qfluentwidgets import SegmentedWidget

from common.server import BananaServer
from components import GridScrollArea, VideoCard
from ..tools import check_result


class VodInterface(GridScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.pivot = SegmentedWidget(self)

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName("VodInterface")
        self.setWidget(self.view)
        self.pivot.move(11, 11)

        self.pivot.addItem('recommend', '推荐')
        self.pivot.addItem('hot', '热门')
        self.pivot.addItem('latest', '最新')
        self.pivot.setCurrentItem('recommend')

        self.setViewportMargins(11, self.pivot.height() + 22, 11, 11)
        self.pivot.currentItemChanged.connect(self.onCurrentItemChanged)

    def init(self):
        if not self.isLoad:
            self.load()
            self.isLoad = True

    def load(self, tp: str = 'recommend'):
        qevent_manager.addTask(BananaServer.vod, tp, self.currentPage, slot=self.onResult)

    def onResult(self, result: dict):
        data = check_result(result)
        if not data:
            return
        vodrows = data['vodrows']
        for vod in vodrows:
            if vod['isvip'] != '0':
                continue
            card = VideoCard(self)
            card.setData(vod)
            self.gridLayout.addWidget(card)
        if self.count() < 16:
            self.nextPage()

    def resizeEvent(self, event: QResizeEvent):
        super().resizeEvent(event)
        self.pivot.resize(self.width() - 22, self.pivot.height())

    def onCurrentItemChanged(self, routeKey: str):
        self.clear()
        self.load(routeKey)

    def nextPage(self):
        super().nextPage()
        self.load(self.pivot.currentRouteKey())
